package com.starlinkdt.proxy.interceptor;

import com.starlinkdt.common.constant.DeductionConstants;
import com.starlinkdt.common.utils.JSONUtils;
import com.starlinkdt.common.utils.oaiauth.OaiServAuthSignUtils;
import com.starlinkdt.proxy.config.CallbackConfig;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author system
 */
@Slf4j
@Component
public class CallbackSignInterceptor extends RetrofitInterceptor {

    @Autowired
    private CallbackConfig callbackConfig;

    @Override
    protected Response doIntercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        HashMap<String, String> oaiParamsMap = new HashMap<>();

        if (originalRequest.body() != null && originalRequest.method().equals("POST")) {
            Buffer buffer = new Buffer();
            originalRequest.body().writeTo(buffer);
            String originalContent = buffer.readUtf8();
            String modifiedContent = modifyBodyContent(originalContent, oaiParamsMap);
            // 处理发送url
            String callbackUrl = signUrl(originalRequest, oaiParamsMap);
            // 创建新的请求体
            RequestBody newBody = RequestBody.create(originalRequest.body().contentType(), modifiedContent);
            Request modifiedRequest = originalRequest.newBuilder()
                    .url(callbackUrl)
                    .addHeader("Authorization", getHeaderSign(oaiParamsMap))
                    .method(originalRequest.method(), newBody)
                    .build();
            Response proceed = chain.proceed(modifiedRequest);
            return proceed;
        }
        return chain.proceed(originalRequest);
    }

    /**
     * 处理signUrl
     * @param request
     * @param oaiParamsMap
     * @return
     */
    private String signUrl(Request request, Map<String,String> oaiParamsMap) {
        String callbackUrl = request.url().url().toString();
        if (request.isHttps()) {
            callbackUrl = callbackUrl.replace(DeductionConstants.DEFAULT_URL, "https:");
        } else {
            callbackUrl = callbackUrl.replace(DeductionConstants.DEFAULT_URL, "http:");
        }
        //utf8解码
        callbackUrl = URLDecoder.decode(callbackUrl, StandardCharsets.UTF_8);
        callbackUrl = callbackUrl.concat("?")
                .concat("a=").concat(oaiParamsMap.get("a"))
                .concat("&t=").concat(oaiParamsMap.get("t"))
                .concat("&u=").concat(oaiParamsMap.get("u"))
                .concat("&key").concat(oaiParamsMap.get("k"));
        return callbackUrl;
    }


    /**
     * 传入Map数据，remove appId/appKey数据
     * @param originalContent
     * @param data 鉴权map数据
     * @return
     */
    private String modifyBodyContent(String originalContent, Map<String,String> data) {
        log.debug("Body Content: {}", originalContent);
        // 在这里实现你的修改逻辑，例如添加或修改某些字段等
        Map<String, Object> map = JSONUtils.parseObject(originalContent, Map.class);
        data.put("a", map.get("appId").toString());
        data.put("k", map.get("appKey").toString());
        data.put("t", String.valueOf(System.currentTimeMillis()));
        data.put("u", "/callback/deduction/result");
        map.remove("appKey");
        map.remove("appId");
        return JSONUtils.toJSONString(map);
    }

    /**
     * 计算签名sign
     * @param data
     * @return
     */
    private String getHeaderSign(Map<String, String> data) {
        try {
            String key = data.get("k");
            data.remove("k");
            return OaiServAuthSignUtils.genSign(data, key);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
